﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using GoodDotNet.Data.Models;
using GoodDotNet.Core.Model;
using GoodDotNet.Core.Model.Enum;

namespace GoodDotNet.WebAdmin.filter
{
    public class APIActionFilter : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
        }
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var modelState = context.ModelState;
            if (!modelState.IsValid)
            {
                string error = string.Empty;
                foreach (var key in modelState.Keys)
                {
                    var state = modelState[key];
                    if (state.Errors.Any())
                    {
                        error = state.Errors.First().ErrorMessage;
                        break;
                    }
                }

                Result result = new Result()
                {

                    code = EnumErrorCode.ErrorCode.CatchError,
                    result = error
                };

                context.Result = new JsonResult(result);
            }
        }
    }
}
